package com.alex.space.commons.date.expression;

import java.util.Calendar;
import java.util.Date;

/**
 * @author Alex
 *         Created by Alex on 2017/12/21.
 *         <p>
 *         绝对日期
 */
public class AbsoluteExpression extends DateExpression {

    @Override
    protected String getRegEx() {
        return "[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\\/(0|[1-9]\\d?\\d?)[ymdqw]";
    }

    @Override
    protected Date generateBaseDate(Date original, int dateSpan, DateUnit dateUnit) {
        Calendar c = Calendar.getInstance();
        c.setTime(original);

        switch (dateUnit) {
            case YEAR:
                c.add(Calendar.YEAR, -1);
                int year = c.get(Calendar.YEAR);
                c.clear();
                c.set(Calendar.YEAR, year);
                c.roll(Calendar.DAY_OF_YEAR, -1);
                break;
            case MONTH:
                c.add(Calendar.MONTH, -1);
                int month = c.get(Calendar.MONTH);
                year = c.get(Calendar.YEAR);
                c.clear();
                c.set(Calendar.YEAR, year);
                c.set(Calendar.MONTH, month);
                c.roll(Calendar.DAY_OF_MONTH, -1);
                break;
            case DAY:
                break;
            case QUARTER:
                int currentMonth = c.get(Calendar.MONTH) + 1;
                if (currentMonth >= 1 && currentMonth <= 3)
                    c.set(Calendar.MONTH, 0);
                else if (currentMonth >= 4 && currentMonth <= 6)
                    c.set(Calendar.MONTH, 3);
                else if (currentMonth >= 7 && currentMonth <= 9)
                    c.set(Calendar.MONTH, 4);
                else if (currentMonth >= 10 && currentMonth <= 12)
                    c.set(Calendar.MONTH, 9);
                c.set(Calendar.DATE, 0);
                break;
            case WEEK:
                c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
                break;
            default:
                break;
        }

        return c.getTime();
    }

    @Override
    protected ExpressionModel getModel() {
        return ExpressionModel.Absolute;
    }
}
